package main

import (
	"fmt"
	"github.com/hashicorp/consul/api"
)



func Register(address string,port int,name string,tags []string,id string)error{
	cfg :=api.DefaultConfig()
	cfg.Address = "192.168.178.120:8500"
	client,err :=api.NewClient(cfg)
	if err != nil {
		panic(err)
	}
	//生成注册对象
	registration :=new(api.AgentServiceRegistration)
	registration.Name = name
	registration.ID = id
	registration.Port = port
	registration.Tags = tags
	registration.Address = address

	//生成对应的检查对象
	check :=&api.AgentServiceCheck{
		HTTP: "http://192.168.178.1:8021/health",
		Timeout: "5s",
		Interval: "5s",
		DeregisterCriticalServiceAfter: "10s",
	}
	registration.Check = check
	err = client.Agent().ServiceRegister(registration)
	if err != nil {
		panic(err)
	}
	return nil
}
//获取所有的服务
func AllServices(){
	cfg :=api.DefaultConfig()
	cfg.Address = "192.168.178.120:8500"
	client,err :=api.NewClient(cfg)
	if err != nil {
		panic(err)
	}
	data,err :=client.Agent().Services()
	if err != nil {
		panic(err)
	}
	for key,_ :=range data{
		fmt.Println(key)
	}
}
func FilterService(){
	cfg :=api.DefaultConfig()
	cfg.Address = "192.168.178.120:8500"
	client,err :=api.NewClient(cfg)
	if err != nil {
		panic(err)
	}
	data,_ :=client.Agent().ServicesWithFilter(`Service =="user-web"`)
	for key,_:=range data{
		fmt.Println(key)
	}
}
func main1(){
	//err :=Register("192.168.178.1",8021,"user-web",[]string{"mxshop","bobby"},"user-web")
	//if err != nil {
	//	panic(err)
	//}
	//AllServices()
	FilterService()
}
